<!-- 增加,编辑,复制角色页面 -->
<template>
  <el-dialog
    v-dialogDrag
    title="角色信息"
    :visible.sync="isDialogFormShow"
    width="50%"
    :before-close="closeDialog"
  >
    <el-form
      ref="roleForm"
      :model="roleForm"
      :rules="roleRule"
      label-position="left"
      label-width="80px"
    >
      <el-row class="roleFormItem">
        <el-col :span="10">
          <el-form-item prop="name" label="角色名称">
            <el-input id="txtRoleName" ref="name" v-model="roleForm.name" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item prop="code" label="角色代码">
            <el-input id="txtRoleCode" ref="code" v-model="roleForm.code" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="roleFormItem">
        <el-col :span="10">
          <el-form-item prop="remark" label="备注">
            <el-input id="txtRemark" ref="remark" v-model="roleForm.remark" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item id="chkYesEnabe" prop="status" label="是否启用">
            <el-radio v-model="roleForm.status" :label="1">是</el-radio>
            <el-radio v-model="roleForm.status" :label="0">否</el-radio>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button id="btnAddRoleOK btnUpdateRoleOK" type="primary" @click="operateRole(operateType, 'roleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  add,
  modify,
  queryRoleById
} from '@/api/right/role'
import { mapActions, mapState } from 'vuex'

export default {
  name: 'DialogForm',
  props: {
    isDialogFormShow: {
      require: true,
      type: Boolean,
      default: false
    },
    operateType: {
      require: true,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 角色信息
      roleForm: {
        code: '',
        name: '',
        remark: '',
        status: '',
        id: '',
        version: '',
        created_by: '',
        companyId: '',
        tenantId: '',
        orgId: ''
      },
      // 角色校验规则
      roleRule: {
        code: [
          { required: true, message: '请输入角色代码', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择角色状态', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    /**
     * 获取角色信息
     */
    ...mapState(
      'user', [
        'roleData'
      ]
    )
  },
  watch: {
    isDialogFormShow: {
      handler(newVal, oldVal) {
        if (!newVal && oldVal) {
          // 关闭弹窗时清楚校验错误提示信息
          this.$refs.roleForm.clearValidate()
        }
      }
    }
  },
  mounted() {
    this.getRole()
    this.$nextTick(function() {
      /**
       * 编辑时根据id获取角色信息
       */
      this.$on('updateRoleFrom', async(row) => {
        this.getRoleDataById(row.id)
      })
    })
  },
  methods: {
    ...mapActions(
      'user', [
        'getRole'
      ]
    ),
    /**
     * 关闭弹窗
     */
    closeDialog() {
      this.roleForm = {
        code: '',
        name: '',
        remark: '',
        status: '',
        id: '',
        modifier: ''
      }
      this.$emit('closeDialog')
    },
    /**
     * 从id获取角色信息
     * @param {*} id 角色Id
     */
    async getRoleDataById(id) {
      try {
        let res = await queryRoleById(id)
        if (res) {
          this.roleForm = res
        } else {
          this.$message.error('获取角色信息失败')
        }
      } catch {
        this.$message.error('网络错误')
      }
    },
    /**
     * 操作角色数据
     * @param {*} operateType 操作类型 add edit copy
     * @param {*} formName ref，用于校验规则
     */
    operateRole(operateType, formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          // 根据不同操作模式，调用不同接口
          this.roleForm.modifier = this.$store.getters.name
          let res = null
          try {
            let isCodeRepeat = false
            // 判断角色编号是否相等
            this.roleData.map(item => {
              if (item.code === this.roleForm.code) {
                isCodeRepeat = true
                return
              }
            })
            // 相等则报错退出函数
            if (isCodeRepeat) {
              this.$message.error('角色编号重复')
              return
            }

            // 调用接口
            if (operateType === 'ADD' || operateType === 'COPY') {
              this.roleForm.version = '1'
              this.roleForm.created_by = '2'
              this.roleForm.companyId = '1'
              this.roleForm.tenantId = '1'
              this.roleForm.orgId = '1337376369553833984'
              res = await add(JSON.parse(JSON.stringify(this.roleForm)))
              if (res) {
                this.$message.success('添加成功')
                this.$emit('operateRoleSuccess')
                this.closeDialog()
              } else {
                this.$message.error('角色代码重复,添加失败')
              }
            }
            if (operateType === 'EDIT') {
              res = await modify(this.roleForm)
              if (res) {
                this.$message.success('修改成功')
                this.$emit('operateRoleSuccess')
                this.closeDialog()
              } else {
                this.$message.error('修改失败')
              }
            }
          } catch {
            this.$message.error('网络错误')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.roleFormItem{
  margin: auto;
  display: flex;
  justify-content: space-between;
}
</style>
